package com.mybatis.service.impl;

import com.mybatis.rds.mapper.ext.UserMapperExt;
import com.mybatis.rds.model.User;
import com.mybatis.module.datasource.annotation.DataSource;
import com.mybatis.module.datasource.enums.DataSourceType;
import com.mybatis.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author: 王霄
 * @date: 2021/8/8 21:26
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapperExt userMapperExt;

    @Override
    @DataSource(DataSourceType.MASTER)
    public User getUserById(int id) {
        return userMapperExt.selectByPrimaryKey(id);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public User getUserById2(int id) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return userMapperExt.selectByPrimaryKey(id);
    }

    @Override
    @DataSource(DataSourceType.MASTER)
    public void addUser(String name) {
        User user = new User();
        user.setName(name);
        userMapperExt.insertSelective(user);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public void addUser2(String name) {
        User user = new User();
        user.setName(name);
        userMapperExt.insertSelective(user);
    }

    @Override
    @Transactional(transactionManager = "master")
    public void dynamicAddUser(String name) {
        addUser(name);
        System.out.println(1 / 0);
        addUser2(name);
    }
}
